﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting;
using System.Text;
using Framework.Common.Attributes;

namespace Framework.Sample
{

    [OrderedDesc("1)    动态创建对象")]
    class Test1 : ITest
    {
        public void Run()
        {
            Console.WriteLine("无参构造创建对象 方法1");
            Assembly asm = Assembly.GetExecutingAssembly();
            object obj = asm.CreateInstance("Framework.Sample.Calculator");
            Console.WriteLine(((Calculator)obj).x);
            Console.ReadLine();

            Console.WriteLine("无参构造创建对象 方法2");
            obj = Activator.CreateInstance(typeof(Calculator));
            Console.WriteLine(((Calculator)obj).x);
            Console.ReadLine();

            Console.WriteLine("使用有参数构造函数创建对象");
            Object[] parameters = new Object[2];    // 定义构造函数需要的参数
            parameters[0] = 3;
            parameters[1] = 5;

            obj = asm.CreateInstance("Framework.Sample.Calculator", true, BindingFlags.Default, null, parameters, null, null);
            Console.WriteLine(((Calculator)obj).x);
            Console.ReadLine();

            Console.WriteLine("Invoke member 实例方法");
            int result = (int)typeof(Calculator).InvokeMember("Add", BindingFlags.InvokeMethod, null, obj, null);
            Console.WriteLine(String.Format("The result is {0}", result));
            Console.ReadLine();

            Console.WriteLine("Invoke member 静态方法");
            result = (int)typeof(Calculator).InvokeMember("Add", BindingFlags.InvokeMethod, null, null, new object[] { 3, 5 });
            Console.WriteLine(String.Format("The result is {0}", result));
            Console.ReadLine();
        }
    }

    public class Calculator
    {

        public int x;
        private int y;

        public Calculator()
        {
            x = 0;
            y = 0;
        }

        public Calculator(int x, int y)
        {
            this.x = x;
            this.y = y;
        }


        public int Add()
        {
            int total = 0;
            total = x + y;
            Console.WriteLine("Invoke Instance Method: ");
            Console.WriteLine(String.Format("[Add]: {0} + {1} = {2}", x, y, total));
            return total;
        }

        public static int Add(int x, int y)
        {
            int total = x + y;
            Console.WriteLine("Invoke Static Method: ");
            Console.WriteLine(String.Format("[Add]: {0} + {1} = {2}", x, y, total));
            return total;
        }
    }
}
